<template>
  <div id="phone">
    <van-nav-bar title="手机号登录" left-text="返回" left-arrow @click-left="onClickLeft" />
    <div id="content">
      <van-field v-model="phone" label="手机号" placeholder="请输入手机号" />
      <van-field v-model="codeSend" center clearable label="验证码" placeholder="请输入短信验证码">
        <template #button>
          <van-button v-if="flag" size="small" type="primary" @click="sendCode()"
            >发送验证码</van-button
          >
          <van-button v-else size="small" @click="sendsCode()">{{ s }}后重新发送</van-button>
        </template>
      </van-field>
      <van-button type="primary" @click="phonelogin()">登录</van-button>
    </div>
  </div>
</template>
<script setup>
import axios from 'axios'
import { da } from 'element-plus/es/locale/index.mjs'
import { showToast } from 'vant'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const onClickLeft = () => history.back()
const phone = ref('')
const codeSend = ref('')
const s = ref(60)
const flag = ref(true)

const sendCode = async () => {
  if (phone.value != '' && phone.value.length == 11) {
    flag.value = !flag.value
    let timer = setInterval(() => {
      s.value--
      if (s.value === 0) {
        flag.value = !flag.value
        clearInterval(timer)
        s.value = 60
      }
    }, 1000)
    let { data } = await axios.post('http://localhost:3000/cj/SMS', { phone: phone.value })
    if (data.code === 200) {
      showToast('发送成功')
      codeSend.value = data.data
    } else {
      showToast('发送失败')
    }
  } else {
    showToast('请输入正确的手机号')
  }
}

const sendsCode = () => {
  if (s.value != 0) {
    showToast('请等待')
  }
}

const phonelogin = async () => {
  let { data } = await axios.post('http://localhost:3000/cj/phoneLogin', {
    phone: phone.value,
    codes: codeSend.value
  })
  if (data.code == 200) {
    router.push('/home')
  } else {
    showToast('登录失败')
  }
}
</script>
<style scoped>
#phone {
  width: 350px;
  height: 844px;
  text-align: center;
  margin: 0 auto;
}
#content {
  width: 100%;
  height: 200px;
  margin-top: 200px;
}
</style>
